
import distributedData from '@ohos.data.distributedData';

const STORE_ID = 'distributedcalc';
const TAG: string = 'BT_Demo[KvStoreModel]'

export class KvStoreModel {
    kvManager;
    kvStore;
    bundleName: string = null

    public init(bundleName: string){
        this.bundleName = bundleName
    }

    createKvStore(callback) {
        if ((typeof (this.kvStore) !== 'undefined')) {
            callback();
            return;
        }
        var config = {
            bundleName: this.bundleName,
            userInfo: {
                userId: '0',
                userType: 0
            }
        };
        console.info(`${TAG} createKVManager begin`);
// @ts-ignore
        distributedData.createKVManager(config).then((manager) => {
            console.log(`${TAG} createKVManager success, kvManager=` + JSON.stringify(manager));
            this.kvManager = manager;
            let options = {
                createIfMissing: true,
                encrypt: false,
                backup: false,
                autoSync: true,
                kvStoreType: 1,
                securityLevel: 1,
            };
            console.info(`${TAG} kvManager.getKVStore begin`);
            this.kvManager.getKVStore(STORE_ID, options).then((store) => {
                console.log(`${TAG} getKVStore success, kvStore=` + store);
                this.kvStore = store;
                callback();
            });
            console.info(`${TAG} kvManager.getKVStore end`);
        });
        console.info(`${TAG} createKVManager end`);
    }

    put(key, value) {
        //console.log(`${TAG} kvStore.put ` + key + `=` + value);
        this.kvStore.put(key, value + 'end').then((data) => {
            //console.log(`${TAG} kvStore.put ` + key + ` finished, data=` + JSON.stringify(data));
        }).catch((err) => {
            console.error(`${TAG} kvStore.put ` + key + ` failed, ` + JSON.stringify(err));
        });
    }

    off() {
        if (this.kvStore !== null) {
            try {
                this.kvStore.off('dataChange');
            } catch(err) {
                console.error(`${TAG} kvStore.off dataChange error:` + err)
            }

        }
    }

    setOnMessageReceivedListener(msg, refreshdata) {
        this.createKvStore(() => {
            this.kvStore.on('dataChange', 1, (data) => {
                let entries = data.insertEntries.length > 0 ? data.insertEntries : data.updateEntries;
                this.simplify(entries, msg, refreshdata)
            });
            console.info(`${TAG} kvStore.on(dataChange) end`);
        });
    }

    simplify(entries, msg, refreshdata) {
        for (let i = 0; i < entries.length; i++) {
            if (entries[i].key === msg) {
                let value = entries[i].value.value;
                let valueResult = value.substring(0, value.lastIndexOf('end'));
                console.log(`${TAG} Entries receive ` + msg + `=` + valueResult);
                refreshdata(valueResult);
                return;
            }
        }
    }
}